package com.schoolhelper.controller.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.constants.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.schoolhelper.model.Model;
import com.schoolhelper.model.dao.okhttp.LwlRequestUrl;
import com.schoolhelper.model.entity.User;
import com.schoolhelper.utils.ImageUtils;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.constant.Api;
import com.schoolhelper.utils.constant.LwlApi;

import java.util.HashMap;
import java.util.Map;

public class SearchContactActivity extends AppCompatActivity {

    private EaseTitleBar searchContactTitleBar;
    private RelativeLayout rlSearchContact;
    private EditText etSearchName;
    private TextView tvContactName;
    private Button btnContactChat;
    private ImageView ivContactPhoto;
    private String username;
    private String phone;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_contact);

        initData();
        
        initListener();
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void initListener() {
        searchContactTitleBar.setOnBackPressListener(v -> finish());
        searchContactTitleBar.setOnRightClickListener(v -> find());

        btnContactChat.setOnClickListener(v -> chat());
    }

    private void chat() {
        if (MyCache.read(getApplicationContext(), "userId") == null) {
            runOnUiThread(() -> {
                Toast.makeText(getApplicationContext(), "您需要先登录才能开始聊天", Toast.LENGTH_SHORT).show();
            });
            Intent toLogin = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(toLogin);
        } else {
            Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
            intent.putExtra(EaseConstant.EXTRA_CONVERSATION_ID, phone);
            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            intent.putExtra(EaseConstant.EXTRA_IS_ROAM, true);
            startActivity(intent);
            finish();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void find() {
        // 获取输入的用户名称
        final String inputPhone = etSearchName.getText().toString();

        // 校验输入的名称
        if (TextUtils.isEmpty(inputPhone)) {
            Toast.makeText(getApplicationContext(), "查询的手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // 去服务器判断当前用户是否存在

        Map<String, String> headers = new HashMap<>();
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("phone", inputPhone);
        String postResponseJson = LwlRequestUrl.getPostResponseJson(LwlApi.BASE_URL, LwlApi.GET_BY_PHONE, headers, requestBody);
        System.out.println("查询结果：" + postResponseJson);
        try {
            User user = JSONObject.parseObject(postResponseJson, User.class);
            username = user.getUsername();
            phone = user.getPhone();
            runOnUiThread(() -> {
                rlSearchContact.setVisibility(View.VISIBLE);
                tvContactName.setText(user.getUsername());
                ivContactPhoto.setImageBitmap(ImageUtils.GetLocalOrNetBitmap(user.getProfileImg(), getApplicationContext()));
            });
        } catch (Exception e) {
            runOnUiThread(() -> {
                Toast.makeText(getApplicationContext(), "查询失败", Toast.LENGTH_SHORT).show();
                rlSearchContact.setVisibility(View.INVISIBLE);
            });
            e.printStackTrace();
        }
    }

    private void initData() {
        searchContactTitleBar = findViewById(R.id.search_contact_title_bar);
        searchContactTitleBar.setRightTitle("查找");

        rlSearchContact = findViewById(R.id.rl_search_contact);
        etSearchName = findViewById(R.id.et_search_name);
        tvContactName = findViewById(R.id.tv_contact_name);
        btnContactChat = findViewById(R.id.btn_contact_chat);
        ivContactPhoto = findViewById(R.id.iv_contact_photo);
    }
}